package com.squareshoot.picCheckin;

import java.io.IOException;
import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.SearchManager;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.SearchRecentSuggestions;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class SearchVenue extends Activity {
	
	double latitude,longitude;
	String username,password;
	ArrayList<String> venues=null;
	final Handler mHandler = new Handler();
	Runnable updateAdapter = null;
	Handler handler;
	Uri photoUri=null;
	String query;
	SearchingTask searchThread;
	boolean sendtotwitter,sendtofacebook;
	
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.searchvenue);
	
	    Intent intent = getIntent();
	    
	    Bundle bundle = intent.getBundleExtra(SearchManager.APP_DATA);
	    latitude = bundle.getDouble("latitude");
	    longitude = bundle.getDouble("longitude");
	    username = bundle.getString("username");
	    password = bundle.getString("password");
	    sendtotwitter = bundle.getBoolean("sendtotwitter");
		sendtofacebook = bundle.getBoolean("sendtofacebook");
		if(bundle.containsKey("photo")){
			photoUri = (Uri)bundle.get("photo");
		}
		
	    handleIntent(intent,savedInstanceState);
	}
    
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putString("query",query);
		outState.putStringArrayList("venues",venues);
	}

	public Object onRetainNonConfigurationInstance() {
		if(searchThread!=null){
			searchThread.setActivity(null);
		}
		return searchThread;
	}
	
	public void onNewIntent(Intent intent){
		handleIntent(intent,null);
	}
	
	private void handleIntent(Intent intent,Bundle savedInstanceState){
		findViewById(R.id.serchLinearLayout).setVisibility(View.VISIBLE);
		findViewById(R.id.searchResultLinear).setVisibility(View.GONE);
	    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
	    	if(getLastNonConfigurationInstance()==null){
    			searchThread=new SearchingTask();
    		}else{
    			searchThread=(SearchingTask) getLastNonConfigurationInstance();
    		}
    		searchThread.setActivity(this);
    		
	    	if(savedInstanceState==null){
	    		String search = intent.getStringExtra(SearchManager.QUERY);
	    		searchThread.execute(search);
	    	}
	    	else{
	    		query = savedInstanceState.getString("query");
	    		venues = savedInstanceState.getStringArrayList("venues");
	    		if(venues!=null)formatVenues();
	    	}
	    }
	}

	private void onThreadCompleted(Bundle data){
		if(!data.containsKey("eMessage")){
			findViewById(R.id.serchLinearLayout).setVisibility(View.GONE);
			findViewById(R.id.searchResultLinear).setVisibility(View.VISIBLE);
			venues = ChooseVenue.fillVenuesArray(data.getString("reponse"));
			query = data.getString("query");
			SearchRecentSuggestions suggestions = new SearchRecentSuggestions(this,VenueSuggestionProvider.AUTHORITY,VenueSuggestionProvider.MODE);
	    	suggestions.saveRecentQuery(query,null); 
			formatVenues();
		}else{
			Toast erreurToast = Toast.makeText(SearchVenue.this,data.getString("eMessage"),Toast.LENGTH_SHORT);
			erreurToast.setGravity(Gravity.CENTER, 0, 0);
			erreurToast.show();
		}
	}
	
	private void formatVenues(){
		
		final ListView searchList = (ListView)findViewById(R.id.searchList);
		final VenuesListAdapter adapter = new VenuesListAdapter(this,venues);
		searchList.setAdapter(adapter);
		setOnClick(searchList);
		
		TextView results = (TextView)findViewById(R.id.searchText);
		results.setText(getString(R.string.results)+" "+query);
	}
	
	private void setOnClick(ListView listVenues){
		listVenues.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View view, int position,long id) {
				String venue = venues.get(position);
				String venueId = null;
				try {
					JSONObject jVenue = new JSONObject(venue);
					venueId = jVenue.getString("id");
				}catch(JSONException e){
					e.printStackTrace();
				}
				Intent i=new Intent(SearchVenue.this,VenueDetails.class);
				Bundle bundle = new Bundle();
				bundle.putString("venueId",venueId);
				bundle.putString("username",username);
				bundle.putString("password",password);
				bundle.putDouble("latitude",latitude);
				bundle.putDouble("longitude",longitude);
				bundle.putBoolean("sendtotwitter",sendtotwitter);
				bundle.putBoolean("sendtofacebook",sendtofacebook);
				if(photoUri!=null)
					bundle.putParcelable("photo",photoUri);
				i.putExtras(bundle);
				startActivity(i);
			}
		});
	}
	
	private class SearchingTask extends AsyncTask<String,String,Message>{
		private SearchVenue activity;
		private boolean completed=false;
		private Message msg;

		@Override
		protected Message doInBackground(String... params) {
			msg = Message.obtain();
			Bundle data = new Bundle();
			String search=params[0].replaceAll(" ","%20");
			String venuesUrl = "http://api.foursquare.com/v1/venues.json?l=30&geolat="+latitude+"&geolong="+longitude+"&q="+search;
			String reponse = null;
			try {
				reponse = Common.getUrlDataAuth(venuesUrl,username,password);
				data.putString("reponse",reponse);
			} catch (IOException e) {
				data.putString("eMessage",e.getMessage());
			}
			data.putString("query",params[0]);
			msg.setData(data);
			return msg;
		}

		@Override
		protected void onPostExecute(Message msg) {
			completed=true;
			this.msg=msg;
			if(activity!=null)
				endTask();
		}
		
		private void setActivity(SearchVenue activity) {
			this.activity = activity;
			if ( completed ) {
				endTask();
			}
		}
		
		private void endTask(){
			activity.searchThread=null;
			activity.onThreadCompleted(msg.getData());
		}
	}
}
